<template>
  <div>
    <el-tabs v-model="searchform.tab" @tab-change="getData">
      <el-tab-pane :label="item.name" :name="item.key" v-for="(item, index) in tabbars" :key="index"></el-tab-pane>
    </el-tabs>
    <el-card shadow="never" class="border-0">
      <!--搜索-->
      <Search :model="searchform" @search="getData" @reset="resetSearchform">
        <SearchItem label="订单编号">
          <el-input v-model="searchform.no" placeholder="订单编号" clearable></el-input>
        </SearchItem>
        
        <template #show>
          <SearchItem label="收货人">
              <el-input v-model="searchform.name" placeholder="收货人"  clearable></el-input>
          </SearchItem>
           <SearchItem label="手机号">
              <el-input v-model="searchform.phone" placeholder="收货人"  clearable></el-input>
          </SearchItem>
           <SearchItem label="开始时间">
               <el-date-picker
              v-model="searchform.starttime"
              type="date"
              placeholder="开始日期"
              style="width: 90%;"
              value-format="YYYY-MM-DD"
              />
          </SearchItem>
          <SearchItem label="结束时间">
              <el-date-picker
              v-model="searchform.endtime"
              type="date"
              placeholder="结束日期"
              style="width: 90%;"
              value-format="YYYY-MM-DD"
              />
          </SearchItem>
        </template>
      </Search>

      <!-- 新增|刷新 -->
      <ListHeader layout="refresh,download" @refresh="getData" @download="handleExportExcel"> 
        <el-button  type="danger" size="small" @click="handleMultiDelete">批量删除</el-button>
      </ListHeader>

      <el-table  ref="multipleTableRef"  @selection-change="handleSelectionChange"  :data="tableData" stripe style="width: 100%" v-loading="loading">
        <el-table-column type="selection" width="55" />
        <el-table-column label="商品" width="300">
          <template #default="{ row }">
           <div>
            <div class="flex text-sm">
            <div class="flex-1">
              <p>订单号:</p>
              <small>{{ row.no }}</small>
            </div>
            <div>
              <p>下单时间:</p>
              <small>{{ row.create_time }}</small>
            </div>
           </div>
           <div class="flex py-2" v-for="(item,index) in row.order_items" :key="index">
            <el-image :src="item.goods_item ? item.goods_item.cover : ''" 
            fit="fill" :lazy="true" style="width: 30px; height: 30px;"></el-image>
            <p class="text-blue-500 ml-2">
              {{ item.goods_item ? item.goods_item.title : '商品已被删除' }}
            </p>
           </div>
           </div>
          </template>
        </el-table-column>

        <el-table-column label="实际付款" width="120" prop="total_price" align="center" />
        <el-table-column align="center" label="买家" width="120">
          <template #default="{ row }">
           <p>{{ row.user.nickname  || row.user.username}}</p>
           <small>(用户ID:{{ row.user.id }})</small>
          </template>
        </el-table-column>


        <el-table-column label="交易状态" width="170" align="center">
          <template #default="{ row }">
            <div>
              付款状态:
              <el-tag v-if="row.payment_method == 'wechat'" type="success" size="small">微信支付</el-tag>
              <el-tag v-else-if="row.payment_method == 'alipay'"  size="small">支付宝支付</el-tag>
              <el-tag v-else type="info" size="small">未支付</el-tag>
            </div>

            <div>
              发货状态:
              <el-tag :type="row.ship_data ? 'success' : 'info'" size="small">{{ row.ship_data ? '已发货' : '未发货' }}</el-tag>
            </div>


            <div>
              收货状态:
               <el-tag :type="row.ship_status == 'received' ? 'success' : 'info'" size="small">
                {{ row.ship_status == 'received' ? '已收货' : '未收货' }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{row}"> <!---声明作用域插槽，接收scope参数-->
           <el-button class="px-1" type="primary" size="small" @click="openInfoModal(row)">订单详情</el-button>
           <el-button v-if="searchform.tab === 'noship'" class="px-1" type="primary" size="small">订单发货</el-button>
           <el-button v-if="searchform.tab === 'refunding'" class="px-1" type="primary" size="small" @click="handleRefund(row.id,1)">同意退款</el-button>
           <el-button v-if="searchform.tab === 'refunding'" class="px-1" type="primary" size="small" @click="handleRefund(row.id,0)">拒绝退款</el-button>
          </template>
        </el-table-column>

      </el-table>

      <div class="flex items-center justify-center mt-5">
        <el-pagination background layout="prev,pager,next" :total="total" :current-page="currentPage" :page-size="limit"
          @current-change="getData" />
      </div>
    </el-card>


    <ExportExcel :tabs="tabbars" ref="ExportExcelRef"/>
    <InfoModal ref="InfoModalRef" :info="info" />
  </div>
</template>

<script setup>
import { ref } from "vue"
import {
  getOrderList,
  deleteOrder,
  refundOrder
} from "@/api/order"

import {
  useInitTable
} from "@/composables/useCommon"
import ListHeader from '@/components/ListHeader.vue'
import Search from '@/components/Search.vue'
import SearchItem from '@/components/SearchItem.vue'
import ExportExcel from './ExportExcel.vue'
import InfoModal from "./InfoModal.vue"
import {
  showModal, //提示框
  showPrompt, //输入框
  toast
} from "@/composables/util"


//二次封装的列表，分页，搜索逻辑
const {

  handleSelectionChange, //给选中的对象添加id
  multipleTableRef, //选中对象的内容
  handleMultiDelete,//批量删除
  searchform,
  resetSearchform,
  tableData,
  loading,
  currentPage,
  total,
  limit,
  getData,
} = useInitTable({
  searchform: {
    no: "",//关键词
    tab: "all", //默认选中全部标签
    starttime: "",
    endtime:"",
    name:"",
    phone:""
  },
  getList: getOrderList,
  onGetListSuccess: (res) => {
    tableData.value = res.list.map((o) => {//拿到图片列表数据
      o.bannersloading = false
      o.contentloading = false
      o.skusloading = false
      return o;
    });
    total.value = res.totalCount; //总数
  },
  delete: deleteOrder
})




const tabbars = [{
  key: "all",
  name: "全部"
}, {
  key: "nopay",
  name: "待支付"
}, {
  key: "shiped",
  name: "待收货"
}, {
  key: "received",
  name: "已收货"
}, {
  key: "finished",
  name: "已完成"
}, {
  key: "closed",
  name: "已关闭"
},
 {
  key: "refunding",
  name: "退款中"
}
]

const ExportExcelRef = ref(null)
const handleExportExcel = ()=>{
    ExportExcelRef.value.open()
}


const InfoModalRef = ref(null)
const info = ref(null)
const openInfoModal = (row)=>{
  row.order_items = row.order_items.map(o=>{
    if(o.skus_type == 1 && o.goods_skus){
      let s = []
      for (const key in o.goods_skus.skus) {
       s.push(o.goods_skus.skus[key].value)//提取每个SKU属性值
      }
     o.sku =  s.join(",")//将数据用,连接并存储在sku字段中
    }
    return o
  })
  info.value = row
  InfoModalRef.value.open()
}

//退款处理
const handleRefund = (id,agree)=>{//当前对象id和判断同意、拒绝的数值agree
  (agree ? showModal("是否同意该订单退款") : showPrompt("请输入拒绝的理由"))
  .then(({value})=>{//弹窗返回的对象中解构出value--弹窗内容
    let data = {agree} //同意退款直接调用API--第一个body参数
    if(!agree){
      data.disagree_reason = value //拒绝理由，第二个body参数
    }
    refundOrder(id,data).then(res=>{
      getData()
      toast("操作成功")
    })
  })
}
</script>